<template>
  <div class ="courseWare">
    <basic-container>
      <avue-crud :option="option"
                 :table-loading="loading"
                 :data="data"
                 :page.sync="page"
                 :permission="permissionList"
                 :before-open="beforeOpen"
                 v-model="form"
                 ref="crud"
                 @row-update="rowUpdate"
                 @row-save="rowSave"
                 @row-del="rowDel"
                 @search-change="searchChange"
                 @search-reset="searchReset"
                 @selection-change="selectionChange"
                 @current-change="currentChange"
                 @size-change="sizeChange"
                 @refresh-change="refreshChange"
                 @on-load="onLoad">
        <template slot="menuLeft" slot-scope="scope">
          <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permissionList" @click="handleDelete">删 除</el-button>
        </template>

        <!-- 播放自定义 -->
       <!-- <template slot-scope="scope" slot="menu">
          <el-button type="text"
                     size="small"
                     icon="el-icon-video-courseware"
                     plain
                     v-if="permission.courseware_play"
                     class="none-border"
                     @click="handlePlayer(scope.row)">播放
          </el-button>
        </template>-->

        <!-- 附件表单自定义 -->
        <template slot="kcwjForm">
          <div v-if="dialogType !== 'view'">
            <el-upload
              action="/api/fileManager/upload/file"
              accept=".pdf,.mp4,.flv"
              :headers="SetHeaders"
              :file-list="kcwjFileList"
              :before-upload="beforeUploadKJ"
              :on-remove="handleRemoveKJ"
              :on-success="uploadKJSuccess">
              <el-button size="small" type="primary">上传课件</el-button>
            </el-upload>
          </div>
        </template>

        <!-- 相关附件表格自定义 -->
        <!--<template slot="zlfj" slot-scope="scope">
          <div v-if="scope.row['wjlx']=='1'">
            <div class="enclosure_div">
              <a :href="downloadHead + scope.row['kcwj']">
                <i class="el-icon-download"></i>下载附件
              </a>
            </div>
          </div>
          <div v-else>
            <div>{{scope.row.kcsp}}</div>
          </div>
        </template>-->

        <template slot="zlfj" slot-scope="scope">
          <div v-if="scope.row['wjlx']=='1'">
            <div class="enclosure_div">
              <a :href="downloadHead + scope.row['kcwj']">
                <i class="el-icon-download"></i>下载附件
              </a>
            </div>
          </div>
          <div v-else="scope.row['wjlx']=='2'">
            <div>
              <el-button type="text"
                         size="small"
                         icon="el-icon-video-courseware"
                         plain
                         v-if="permission.courseware_play"
                         class="none-border"
                         @click="handlePlayer(scope.row)">播放
              </el-button>
            </div>
          </div>
        </template>

      </avue-crud>

      <!--视频弹窗-->
      <el-dialog
        title="视频播放"
        append-to-body
        :visible.sync="PlayerBox"
        @close="closePlay"
        width="555px">
        <LivePlayer :videoUrl="videoUrl" live muted stretch playback-rate></LivePlayer>
      </el-dialog>

    </basic-container>
  </div>

</template>

<script>
  import {getList, getDetail, add, update, remove,getkcsp} from "@/api/jypx/educourseware/courseware";
  import {mapGetters} from "vuex";
  import LivePlayer from "@liveqing/liveplayer";
  import {validateDigit} from "@/api/jypx/educourseware/validate";
  import { getToken } from "@/util/auth";

  export default {

    data() {
      return {
        scr:"",
        userName:"",
        videoUrl:'',
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          playBth: true,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "",
              prop: "id",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "资料标题",
              prop: "zlbt",
              align: "center",
              search: true,
              slot: false,
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },

            {
              label: "所属类别",
              prop: "sslb",
              align: "center",
              type: "select",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=pxlb",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },

            {
              label: "上传人",
              prop: "scr",
              align: "center",
              dicData: [],
              type: "select",
              row: false,
              dicUrl: "/api/eduCourseware/courseware/getScrList",
              addDisplay: false,
              editDisplay: false,
              props: {
                label: "realName",
                value: "id",
              },
              checkStrictly: true,
              disabled: true
            },
            {
              label: "上传日期",
              prop: "scrq",
              align: "center",
              type: "datetime",
              format: "yyyy-MM-dd HH:mm:ss",
              valueFormat: "yyyy-MM-dd HH:mm:ss",
              addDisplay: false,
              editDisplay: false,
            },
            {
              label: "关键字",
              prop: "gjz",
              align: "center",
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "",
              prop: "kjlx",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },

            {
              label: "文件类型",
              type:"select",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=courseware_type",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dataType: "number",
              hide: false,
              prop: "wjlx",
              align: "center",
              rules: [{
                required: true,
                message: "请输入文件或视频",
                trigger: "blur"
              }]
            },
            {
              label: "教程简介",
              prop: "jcjj",
              align: "center",
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "课件文件",
              prop: "kcwj",
              align: "center",
              slot: true,
              formslot: true,
              hide: true,
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },

            {
              label: "课件视频",
              prop: "kcsp",
              align: "center",
              hide: true,
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "资料附件",
              prop: "zlfj",
              align: "center",
              slot: true,
              hide: false,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
          ]
        },
        data: [],
        // 上传课件
        kcwjFileList: [],
        scrq: [],
        //下载课件
        downloadHead: "/api/fileManager/download/",
        dialogType: "",
        PlayerBox: false,
        scrList: {},
        SetHeaders: { "Blade-Auth": getToken() },
      };
    },
    components: {
      LivePlayer
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.courseware_add, true),
          viewBtn: this.vaildData(this.permission.courseware_view, true),
          /*delBtn: false,*/
          editBtn: this.vaildData(this.permission.courseware_edit, true),
          playBth: this.vaildData(this.permission.courseware_play, true)

        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      },
      player () {
        return this. $refs. videoPlayer. player
      },
    },

    methods: {
      closePlay(){
        this.PlayerBox=false;
        this.videoUrl=""
      },
      // 弹出视频
      handlePlayer(row) {
        debugger
        this.PlayerBox=true
        getkcsp(row.id).then(response => {
          this.url =response.data.data;
          this.videoUrl= this.url
        });
      },

      /**
       * 上传附件
       */
      // 上传附件前
      beforeUploadKJ(file) {
        this.isFailed = false;
        var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
        console.log(testmsg)
        const extension = testmsg === 'pdf'
        const extension2 = testmsg === 'mp4'
        const extension3 = testmsg === 'flv'
        var isLimit = this.kcwjFileList.length + 1 <= 1;
        if (!isLimit) {
          this.$message.warning("只能选择一个附件!");
          return isLimit;
        }else if(!extension && !extension2 && !extension3) {
          this.$message.warning('请上传 .pdf,.mp4,.flv 标准格式文件!');
          return this.isFailed;
        }
      },

      // 上传附件成功
      uploadKJSuccess(response, file, fileList) {
        if (response.code !== 200 || response.success !== true) {
          return;
        }
        this.kcwjFileList = fileList;
        this.form.kcwj = response.data.id;
        console.log(this.form.kcwj)
      },

      // 删除附件
      handleRemoveKJ(file, fileList) {
        this.kcwjFileList = fileList;
        this.form.kcwj = "";
      },
      //新增
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },

      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },

      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },

      beforeOpen(done, type) {
        this.kcwjFileList = [];
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
            if (type === "edit") {
              if(JSON.stringify(this.form.bladeFile)!="{}")
              this.kcwjFileList.push({
                name: this.form.bladeFile.fileName,
                response: {
                  code: 200,
                  success: true,
                  msg: "操作成功",
                  data: this.form.bladeFile
                }
              });
            } else {
              this.form.kcwj = this.form.bladeFile.fileName;
            }
          });
        }
        this.dialogType = type;
        done();
      },

      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    },

    //监听
    watch: {
      'form.wjlx':{
        handler(val){
          const kcwj =this.findObject(this.option.column,'kcwj')
          const kcsp = this.findObject(this.option.column,'kcsp')
          if(val===1){
            kcwj.display=true
            kcsp.display=false
            kcwj.rules=[{
              required: true,
              validator: validateDigit,
              trigger: "blur"
            }]
          }else if(val===2){
            kcsp.display=true
            kcwj.display=false
            kcsp.rules=[{
              required:true,
              message: "请输入视频地址",
              trigger:"blur"
            }]
          }else {
            kcwj.display=false
            kcsp.display=false
            kcwj.rules=[]
            kcsp.rules=[]
          }
        },
        immediate: true,
      }
    },

  };
</script>

<style lang="scss" scpoed>
  .courseWare {
    .avue-crud {
      .avue-crud__search {
        .avue-form__row:nth-child(1) {
          .el-form-item__label {
            text-align: unset;
            width: 90px !important;
          }

          .el-form-item__content {
            margin-left: 90px !important;
          }
        }
      }
    }

    .enclosure_div {
      a {
        font-size: 12px;
        color: #409eff;

        i {
          margin-right: 5px;
        }
      }
    }
  }

  .avue-dialog {
    .el-dialog {
      .avue-group {
        .avue-form__group {
          .el-form-item {
            .el-form-item__label {
              width: 110px !important;
            }

            .el-form-item__content {
              margin-left: 110px !important;
            }
          }
        }
      }
    }
  }

</style>
